package com.sheep.dynamic.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.sheep.dynamic.entity.DataSourceMeta;
import com.sheep.dynamic.service.DataSourceMetaService;
import com.sheep.dynamic.util.InitDBUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源配置
 *
 * @author 第七人格
 * @date 2023/04/13
 */
@Component
@Slf4j
public class DynamicDataSourceConfig {

    /**
     * 缓存
     */
    private final Map<String, String> cache = new HashMap<>();

    /**
     * 数据源元数据服务
     */
    @Resource
    private DataSourceMetaService dataSourceMetaService;

    /**
     * 数据源
     */
    @Resource
    private DynamicRoutingDataSource dataSource;

    /**
     * 加载所有数据库
     */
    @PostConstruct
    public void loadAllDB(){
        cache.put("master","管理中心");
        List<DataSourceMeta> dataSourceMetas = dataSourceMetaService.selectAvailable(new DataSourceMeta());
        for (DataSourceMeta datasourceMeta : dataSourceMetas){
            DruidDataSource tmpdb = InitDBUtil.getInitDBConfig();
            tmpdb.setUsername(datasourceMeta.getUsername());
            tmpdb.setPassword(datasourceMeta.getPassword());
            tmpdb.setUrl("jdbc:mysql://"+ datasourceMeta.getUrl()+"/"+ datasourceMeta.getMysqlSchema()+"?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true");
            dataSource.addDataSource(datasourceMeta.getMysqlSchema(),tmpdb);
            log.info("======加载动态数据库完成：mysqlSchema={}",datasourceMeta.getMysqlSchema());
            cache.put(datasourceMeta.getMysqlSchema(), datasourceMeta.getName());
        }
    }

    /**
     * 动态添加数据库
     *
     * @param datasourceMeta 数据源元
     */
    public void addDB(DataSourceMeta datasourceMeta){
        DruidDataSource tmpdb = InitDBUtil.getInitDBConfig();
        tmpdb.setUsername(datasourceMeta.getUsername());
        tmpdb.setPassword(datasourceMeta.getPassword());
        tmpdb.setUrl("jdbc:mysql://"+ datasourceMeta.getUrl()+"/"+ datasourceMeta.getMysqlSchema()+"?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true");
        dataSource.addDataSource(datasourceMeta.getMysqlSchema(),tmpdb);
        log.info("======动态添加数据库完成：mysqlSchema={}",datasourceMeta.getMysqlSchema());
        cache.put(datasourceMeta.getMysqlSchema(), datasourceMeta.getName());
    }

    /**
     * 动态删除数据库
     *
     * @param datasourceMeta 数据源元
     */
    public void deleteDB(DataSourceMeta datasourceMeta){
        dataSource.removeDataSource(datasourceMeta.getMysqlSchema());
        log.info("======动态删除数据库完成：mysqlSchema={}",datasourceMeta.getMysqlSchema());
        cache.remove(datasourceMeta.getMysqlSchema());
    }

    /**
     * 通过schema获取在元数据中的名称
     *
     * @param schema 模式
     * @return {@link String}
     */
    public String getNameBySchema(String schema){
        return cache.getOrDefault(schema, "");
    }
}
